<?php


namespace App\Repositories;


use Illuminate\Support\Str;
use LTools\Repositories\RepositoryAbstract;
use Throwable as ThrowableAlias;

class Customer extends RepositoryAbstract
{
    /**
     * Customer constructor.
     * @param \App\Models\Customer $model
     * @author luffyzhao@vip.126.com
     */
    public function __construct(\App\Models\Customer $model)
    {
        $this->model = $model;
    }

    /**
     * @param array $attributes
     * @return bool|\Illuminate\Database\Eloquent\Model
     * @author luffyzhao@vip.126.com
     */
    public function create(array $attributes = [])
    {
        return parent::create($attributes);
    }

    /**
     * @param $id
     * @return \Illuminate\Database\Eloquent\Model
     * @author luffyzhao@vip.126.com
     */
    public function edit($id)
    {
        return $this->find($id);
    }

    /**
     * @param $id
     * @param array $attributes
     * @throws ThrowableAlias
     * @author luffyzhao@vip.126.com
     */
    public function account($id, array $attributes)
    {
        /** @var \App\Models\Customer $model */
        $model = $this->find($id);
        /** @var \App\Models\CustomerUser $user */
        $user = $model->master()->first();
        /** @var CustomerUser $customerUser */
        $customerUser = app(CustomerUser::class);
        $attributes['customer_id'] = $model->getKey();
        if (is_null($user)) {
            $customerUser->createMasterUser($attributes);
        } else {
            $customerUser->updateMasterUser($user, $attributes);
        }
    }

    /**
     * @param $id
     * @return \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Relations\HasOne|object|null
     * @author luffyzhao@vip.126.com
     */
    public function getAccount($id)
    {
        /** @var \App\Models\Customer $model */
        $model = $this->find($id);
        /** @var \App\Models\CustomerUser $user */
        return $model->master()->first();
    }
}
